/**
 * This is DataActivity.
 * @author fufeng
 * @Time 2023-6-22
 */

package com.example.myapplication.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.db.Data;
import com.example.myapplication.db.SQLiteManager;
import com.example.myapplication.fragment.SensorFragment;
import com.example.myapplication.listview.SellerBean;
import com.example.myapplication.services.MQTTService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class DataActivity extends AppCompatActivity {
    private TextView textView;
    private Spinner spinner;
    private TextView batteryLevel;//用于显示电池电量
    private Switch switchNode;//用于开关节点
    private CheckBox io0;
    private CheckBox io1;
    private CheckBox io2;
    private CheckBox io3;
    private Button send;
    private boolean io0Flag = false;
    private boolean io1Flag = false;
    private boolean io2Flag = false;
    private boolean io3Flag = false;
    private boolean switchFlag = true;
    private int sendNum = 0;
    private boolean sendIntend = false;
    private String nodeStatus;
    private static List<String> SensorItem = new ArrayList<String>();//存储各个传感器类型的容器
    private Handler handler;//用于处理MQTT返回的数据

    private String GatewayID;//用于接收启动Activity时传入的龙芯节点名
    private String GatewayType;
    private String NodeName;//用于接收启动Activity时传入的传感器节点名
    private int sensorNum;//用于接收启动Activity时传入的传感器
    private String SensorTypeArray;

    private SQLiteManager helper;
    private SQLiteDatabase db;
    private final Timer timer = new Timer();//用于定时执行折线图数据更新
    Cursor cursor1;
    private int maxHistoryNum;
    private SimpleDateFormat df = new SimpleDateFormat(Data.DATE_FORMAT_Y);//设置日期格式
    List<SellerBean> dataSource = new ArrayList();// 设置表格数据源
    /**
     * 用于规避重复数据，因为数据上传时间是不固定的，但是定时器更新数据时间是固定的，所以每次查询最后一行数据时
     * 难免会查到上次的数据，所以通过记录上次成功查询的数据的索引，在这次查询时和上次的对比，就可以知道是不是新数据
     * */
    private int SensorDataIndex = 0;

    @SuppressLint("Range")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_data);

         handler = new Handler(){

            @SuppressLint({"SetTextIl8n", "HandlerLeak"})

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                switch (msg.what) {

                    case 1: //更新布局
                        String bat = msg.getData().getString(Data.COLUMN_BatteryLevel);
                        String cmd = msg.getData().getString(Data.NodeStatus);
                        batteryLevel.setText("电量:  "+bat + "%");//更新电量
                        updateNodeStatus(cmd);

                        break;

                    case 2:
                        textView.setText(msg.getData().getString(Data.COLUMN_NodeName));
                        break;

                    default:

                        break;
                }
            }
        };
        textView = (TextView) findViewById(R.id.tv2);
        textView.setText("I'm DataFragment");
        batteryLevel = (TextView)findViewById(R.id.batteryLevel);
        switchNode = (Switch) findViewById(R.id.switchNode);
        /**
         * 设置SwitchButton点击事件为向MQTT发送节点控制命令，命令为控制当前节点是否发送数据，也就是控制节点的上下线
         * */
        switchNode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switchFlag = !switchFlag;
            }
        });

        spinner = findViewById(R.id.spinner);
        io0 = findViewById(R.id.io0);
        io1 = findViewById(R.id.io1);
        io2 = findViewById(R.id.io2);
        io3 = findViewById(R.id.io3);
        io0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                io0Flag = !io0Flag;
            }
        });
        io1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                io1Flag = !io1Flag;
            }
        });
        io2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                io2Flag = !io2Flag;
            }
        });
        io3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                io3Flag = !io3Flag;
            }
        });
        send = findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sendNum == 0){
                    sendNum++;
                    send.setBackgroundColor(Color.RED);
                    sendIntend = true;
                    Toast.makeText(DataActivity.this, "进入命令编辑", Toast.LENGTH_SHORT).show();
                }else if(sendNum == 1){
                    AlertDialog alertDialog2 = new AlertDialog.Builder(DataActivity.this)
                            .setTitle("是否发送命令？")
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    byte cmd = 0x00;
                                    Bundle bundle = new Bundle();
                                    bundle.putString(Data.COLUMN_Gateway, GatewayID);
                                    bundle.putString(Data.COLUMN_NodeName, NodeName);

                                    if(io0Flag){
                                        cmd |= 0x40;
                                    }
                                    if(io1Flag){
                                        cmd |= 0x20;
                                    }
                                    if(io2Flag){
                                        cmd |= 0x10;
                                    }
                                    if(io3Flag){
                                        cmd |= 0x08;
                                    }
                                    if(switchFlag){
                                        cmd |= 0x01;
                                    }
                                    System.out.println("CMD:" + cmd);
                                    bundle.putByte(Data.TopicControlNodeCmd, cmd);
                                    sendControlNodeCMD(bundle);
                                    sendNum = 0;
                                    send.setBackgroundColor(Color.BLUE);
                                    sendIntend = false;
                                }
                            })

                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(DataActivity.this, "取消发送", Toast.LENGTH_SHORT).show();
                                    sendNum = 0;
                                    send.setBackgroundColor(Color.BLUE);
                                    sendIntend = false;
                                }
                            })
                            .create();
                    alertDialog2.show();


                }
            }
        });

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        SensorItem.clear();
        if(bundle != null) {
            GatewayID = bundle.getString(Data.COLUMN_Gateway);
            GatewayType = bundle.getString(Data.COLUMN_GatewayType);
            NodeName= bundle.getString(Data.COLUMN_NodeName);
            sensorNum = bundle.getInt(Data.COLUMN_SensorNum);
            Message message = new Message();
            message.what = 2;
            message.obj = NodeName;
            Bundle bundle1 = new Bundle();
            bundle1.putString(Data.COLUMN_NodeName, "节点ID："+NodeName);
            message.setData(bundle1);
            handler.sendMessage(message);

            SensorTypeArray = bundle.getString(Data.COLUMN_SensorTypeArray);
            if(SensorTypeArray != null){
                try {
                    String[] str = SensorTypeArray.split("_");
                    for(int i = 0; i < str.length; i++) {
                        if(!str[i].equals(Data.NodeStatus)){
                            SensorItem.add(str[i]);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(DataActivity.this,
                android.R.layout.simple_list_item_1, SensorItem);
        spinner.setAdapter(adapter);

        helper = new SQLiteManager(this);



        Bundle bundle1 = new Bundle();
        bundle1.putString(Data.COLUMN_Gateway, GatewayID);
        bundle1.putString(Data.COLUMN_NodeName, NodeName);
        bundle1.putInt(Data.COLUMN_SensorNum, sensorNum);
        bundle1.putString(Data.COLUMN_SensorTypeArray, SensorTypeArray);
        SensorFragment temp_hump = SensorFragment.newInstance(bundle1);
        getFragmentManager().beginTransaction().replace(R.id.chart, temp_hump,
                "mainFragment").commitAllowingStateLoss();

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString(Data.COLUMN_Gateway, GatewayID);
                bundle.putString(Data.COLUMN_NodeName, NodeName);
                bundle.putInt(Data.COLUMN_SensorNum, sensorNum);
                bundle.putString(Data.COLUMN_SensorTypeArray, SensorTypeArray);
                SensorFragment fragment0 = SensorFragment.newInstance(bundle);
                bundle.putInt(Data.SENSORINDEX, position + 1); //刨除节点状态项
                getFragmentManager().beginTransaction().replace(R.id.chart,
                        fragment0, "sensorFragment").commitAllowingStateLoss();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        /**
         * 设置定时器，定时查询数据库是否有新数据，有的话更新在折线图和表格中
         * */
        timer.scheduleAtFixedRate(new TimerTask() {
            @SuppressLint("Range")
            @Override
            public void run() {
// TODO Auto-generated method stub

                db = helper.getReadableDatabase();
                cursor1 = db.query(Data.SensorData_Table, new String[]{Data.COLUMN_Index,Data.COLUMN_SensorData0, Data.COLUMN_BatteryLevel},
                        Data.COLUMN_Gateway +"=? and " + Data.COLUMN_NodeName+"=?", new String[]{GatewayID, NodeName}, null, null, null);

                boolean i = true;
                int m;
                if(cursor1.moveToLast()){
                    do{
                        m = cursor1.getInt(cursor1.getColumnIndex(Data.COLUMN_Index));
                        if(m>SensorDataIndex){

                            nodeStatus = cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_SensorData0));
                            Message message = new Message();
                            message.what = 1;
                            Bundle bundle2 = new Bundle();
                            bundle2.putString(Data.COLUMN_BatteryLevel, String.valueOf(cursor1.getInt(cursor1.getColumnIndex(Data.COLUMN_BatteryLevel))));
                            bundle2.putString(Data.NodeStatus, nodeStatus);
                            message.setData(bundle2);
                            handler.sendMessage(message);
                            SensorDataIndex = cursor1.getInt(cursor1.getColumnIndex(Data.COLUMN_Index));//为下一轮做准备
                            i = false;
                        }
                    }while (cursor1.moveToPrevious() && i);
                }
                cursor1.close();
                db.close();
            }
        }, 100, 1000);


    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        db.close();
    }

    public void updateNodeStatus(String nodeStatus){
        byte cmd = (byte)Integer.parseInt(nodeStatus); //需要控制的节点
        if((cmd & 0x40) != 0 && !sendIntend && switchFlag){
            io0.setChecked(true);
        }else if(!sendIntend){
            io0.setChecked(false);
        }
        if((cmd & 0x20) != 0 && !sendIntend && switchFlag){
            io1.setChecked(true);
        }else if(!sendIntend){
            io1.setChecked(false);
        }
        if((cmd & 0x10) != 0 && !sendIntend && switchFlag){
            io2.setChecked(true);
        }else if(!sendIntend){
            io2.setChecked(false);
        }
        if((cmd & 0x08) != 0 && !sendIntend && switchFlag){
            io3.setChecked(true);
        }else if(!sendIntend){
            io3.setChecked(false);
        }

        if((cmd & 0x01) != 0 && !sendIntend && switchFlag){
            switchNode.setChecked(true);
        }else if(!sendIntend){
            switchNode.setChecked(false);
        }
    }

    /**
     * param bundle 构造命令所需的数据
     * Description 发送控制节点的命令给MQTT服务器
     * */

    public void sendControlNodeCMD(Bundle bundle) {
        String LoongsonID = bundle.getString(Data.COLUMN_Gateway);
        String NodeName = bundle.getString(Data.COLUMN_NodeName);
        byte cmd = bundle.getByte(Data.TopicControlNodeCmd);
        String payload = NodeName + "_" + String.valueOf(cmd);
        System.out.println(payload);

        Message message = new Message();
        Bundle bd = new Bundle();
        bd.putString(Data.MQTTPublishMessage, payload);
        message.what = 33;
        message.obj = LoongsonID + Data.TopicControlNodeCmd;
        message.setData(bd);
        Toast.makeText(DataActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
        MQTTService.handler.sendMessage(message);//Tips:节点名_命令
        //mqtt.publishMessage(LoongsonID + Data.TopicControlNodeCmd, payload);

        //mqtt.publishMessage(LoongsonID + Data.TopicControlNodeCmd,NodeName+"_"+sensorType+"_"+cmd);//Tips:节点名_命令
    }
}
